package com.lollipop.ucenter.shiro;

import java.io.Serializable;
import java.util.Set;

import com.lollipop.common.utils.Encodes;
import com.lollipop.ucenter.rpc.api.RoleService;
import com.lollipop.ucenter.rpc.api.UserService;
import com.lollipop.ucenter.rpc.model.Role;
import com.lollipop.ucenter.rpc.model.User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = userService.findByUsername(username);
        if (user == null) {
            if (log.isDebugEnabled())
                log.debug("{} not found username ", username);
            throw new UnknownAccountException("not found username " + username);
        }
        byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16));
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getUsername()),
                user.getPassword().substring(16), getName());
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt));
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        Set<String> pers = userService.findUserPermissions(shiroUser.getId());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<Role> roles = roleService.findRolesByUserId(shiroUser.getId());
        if (CollectionUtils.isNotEmpty(roles)) {
            for (Role role : roles) {
                authorizationInfo.addRole(role.getName());
            }
        }
        authorizationInfo.setStringPermissions(pers);
        return authorizationInfo;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    public static class ShiroUser implements Serializable {
        private static final long serialVersionUID = 1L;
        String id;
        String name;
    }

}
